﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Diagnostics;
using System.Security.Permissions;

namespace MessageCallAspect.Inspector.MessageSink
{
    [DebuggerStepThrough]
    public class EndpointSink : IMessageSink
    {
        private readonly object m_Target;

        public EndpointSink(object target)
        {
            m_Target = target;
        }

        #region IMessageSink Members

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            throw new NotImplementedException();
        }

        public virtual IMessageSink NextSink
        {
            get
            {
                return null;
            }
        }
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
        public IMessage SyncProcessMessage(IMessage msg)
        {
            Debug.WriteLine("Step into: EndPointSink");
            msg.ValidateParameters();
            IMethodCallMessage methodMessage = new MethodCallMessageWrapper((IMethodCallMessage)msg);
            ReturnMessage returnMessage = null;
            try
            {
                object value = methodMessage.MethodBase.Invoke(m_Target, methodMessage.Args);
                returnMessage = new ReturnMessage(value, methodMessage.Args, methodMessage.ArgCount, methodMessage.LogicalCallContext, methodMessage);
            }
            catch (Exception ex)
            {
                return ex.Wrap(msg);
            }
            return returnMessage;
        }

        #endregion

    }
}